package coreservlets;

import java.sql.*;

/**
 * A JDBC example that connects to the MicroSoft Access sample Northwind
 * database, issues a simple SQL query to the employee table, and prints the
 * results.
 */
public class NorthwindTest {
	public static void main(String[] args) {
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/myApp";
		String username = "root"; // No username/password required
		String password = "mysql"; // for desktop access to MS Access.
		showEmployeeTable(driver, url, username, password);
	}

	/**
	 * Query the employee table and print the first and last names.
	 */
	public static void showEmployeeTable(String driver, String url,
			String username, String password) {
		try {
			// Load database driver if it's not already loaded.
			Class.forName(driver);
			// Establish network connection to database.
			Connection connection = DriverManager.getConnection(url, username,
					password);
			System.out.println("Employees\n" + "==========");
			// Create a statement for executing queries.
			Statement statement = connection.createStatement();
			String query = "SELECT firstname, secondname FROM employee";
			// Send query to database and store results.
			ResultSet resultSet = statement.executeQuery(query);
			// Print results.
			while (resultSet.next()) {
				System.out.print(resultSet.getString("firstname") + " ");
				System.out.println(resultSet.getString("secondname"));
			}
			DatabaseMetaData dbMetaData = connection.getMetaData();
			String productName =
			dbMetaData.getDatabaseProductName();
			System.out.println("Database: " + productName);
			String productVersion =
			dbMetaData.getDatabaseProductVersion();
			System.out.println("Version: " + productVersion);
			connection.close();
		} catch (ClassNotFoundException cnfe) {
			System.err.println("Error loading driver: " + cnfe);
		} catch (SQLException sqle) {
			System.err.println("Error with connection: " + sqle);
		}
	}
}
